<?php
/**
 * @version $Id: image_resizer.controller.php 6 2010-03-07 22:36:34Z oystein.rg $
 * @licence http://www.opensource.org/licenses/bsd-license.php The BSD License
 * @copyright Upstruct Berlin Oslo
 */

/**
 * @author     Øystein Riiser Gundersen <oystein@upstruct.com>
 * @package    ImageKit
 * @version    $Revision: 6 $
 */
class ImageResizerController extends Controller {
	
	protected $SUPPORTED_IMAGE_TYPES = array(
		MIMEType::JPEG => 'imagecreatefromjpeg',
		MIMEType::GIF  => 'imagecreatefromgif',
		MIMEType::PNG  => 'imagecreatefrompng'
	);
	
	protected function initialize() {
		if (!function_exists('gd_info'))
			throw new CobwebException('ImageKit requires the GD imaging library PHP extension!');
		ini_set('gd.jpeg_ignore_warning', 1);
	}
	
	/**
	 * CacheControl({'max_age'=43200})
	 * @LoggingDisabled
	 */
	public function resize($image_filename, $width = NULL, $height = NULL, $base_path = COBWEB_WWW_ROOT, $cache_base_path = NULL) {
		
		$file = realpath($base_path . '/' . $image_filename);

		if (!$file || !str_starts_with($file, realpath($base_path)) || !file_exists($file))
			throw new HTTP404();
		
		list($old_width, $old_height) = getimagesize($file);
		
		$mime_type = MIMEType::guess($file);
		$image_constructor = $this->getImageConstructor($mime_type);		
		if (!$image = $image_constructor($file))
			throw new CobwebException('Failed to create image');
		
		$ratio = $old_width / $old_height;
		if ($width && !$height)
			$height = $width / $ratio;
		else if ($height && !$width)
			$width = $height * $ratio;
		else if (!$height && !$width) {
			$height = $old_height;
			$width = $old_width;
		}
		
		$resized = imagecreatetruecolor($width, $height);
		imagealphablending($resized, true);
		imagesavealpha($resized, true);
		imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $old_width, $old_height);
		
		$cache_image_path = NULL;
		if (!is_null($cache_base_path)) {
			$cache_image_path = $cache_base_path . $this->request->path();
			$cache_directory = dirname($cache_image_path);
			if (!file_exists($cache_directory))
				mkdir($cache_directory, 0755, true);
		}
		
		$response = new ImageResponse($resized, $mime_type, $cache_image_path);
		
		// $response['Last-Modified'] = $last_modification->format(DateTime::RFC1123);
		return $response;
	}
	
	protected function getImageConstructor($mime_type) {
		if (!isset($this->SUPPORTED_IMAGE_TYPES[$mime_type]))
			throw new CobwebException('Unsupported image type');
		return $this->SUPPORTED_IMAGE_TYPES[$mime_type];
	}

	
	
}
